package site.huoqiang.emos.task;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import site.huoqiang.emos.exception.EmosException;
import site.huoqiang.emos.mapper.LeaveMapper;
import site.huoqiang.emos.mapper.UserMapper;

import java.util.HashMap;

/**
 * @author: huoqiang huoqiang
 * @date: 2022-03-28
 */
@Component
@Slf4j
public class LeaveWorkflowTask {

    @Value("${emos.code}")
    private String code;

    @Value("${emos.tcode}")
    private String tcode;

    @Value("${workflow.url}")
    private String workflow;

    @Value("${emos.recieveNotify}")
    private String recieveNotity;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LeaveMapper leaveMapper;

    /**
     * 异步开启请假工程流
     *
     * @param id        请假记录ID
     * @param creatorId 申请人ID
     * @param days      请假天数
     */
    @Async("AsyncTaskExecutor")
    public void startLeaveWorkflow(int id, int creatorId, String days) {
        HashMap info = userMapper.searchUserInfo(creatorId);
        JSONObject json = new JSONObject();
        json.set("url", recieveNotity);
        json.set("creatorId", creatorId);
        json.set("creatorName", info.get("name").toString());
        json.set("code", code);
        json.set("tcode", tcode);
        json.set("title", info.get("dept").toString() + info.get("name").toString() + "的请假");
        Integer managerId = userMapper.searchDeptManagerId(creatorId);
        json.set("managerId", managerId);
        Integer gmId = userMapper.searchGmId();
        json.set("gmId", gmId);
        json.set("days", Double.parseDouble(days));

        // 发起请求
        String url = workflow + "/workflow/startLeaveProcess";
        HttpResponse response = HttpRequest.post(url).header("content-type", "application/json").body(json.toString()).execute();
        if (response.getStatus() == HttpStatus.HTTP_OK) {
            json = JSONUtil.parseObj(response.body());
            // 获取InstanceID
            String instanceId = json.getStr("instanceId");
            // 更新请假InstanceId
            HashMap param = new HashMap(2) {{
                put("id", id);
                put("instanceId", instanceId);
            }};
            int rows = leaveMapper.updateLeaveInstanceId(param);

            if (rows != 1) {
                throw new EmosException("保存请假工作流实例ID失败");
            }
        } else {
            log.error(response.body());
        }
    }

    /**
     * 删除请假工作流
     *
     * @param instanceId 工作流ID
     * @param type       工作流类型
     * @param reason     删除原因
     */
    @Async("AsyncTaskExecutor")
    public void deleteLeaveWorkflow(String instanceId, String type, String reason) {
        JSONObject json = new JSONObject();
        json.set("instanceId", instanceId);
        json.set("type", type);
        json.set("reason", reason);
        json.set("code", code);
        json.set("tcode", tcode);

        String url = workflow + "/workflow/deleteProcessById";
        HttpResponse response = HttpRequest.post(url).header("content-type", "application/json").body(json.toString()).execute();
        if (response.getStatus() != HttpStatus.HTTP_OK) {
            log.error(response.body());
            throw new EmosException("请假工作流删除失败");
        }
    }

}
